package com.shanghaionstar.activity.webview.handler.picture;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.shanghaionstar.R;
import com.shanghaionstar.weight.TopLayout;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static android.provider.ContactsContract.CommonDataKinds.StructuredName.PREFIX;

public class SelectPicActivity extends BaseActivity
{

    private static final int READ_EXTERNAL_STORAGE = 0x1;

    private static final int TAKE_PHOTO_CODE = 0x0006;

    GridView gvFromLocal;

    private FindImageHelper mFindImageHelper;

    private ImportImagesData data;

    private LoadAndDisplayTask mLoadDisplayTask;

    private LocalPicListAdapter listAdapter;


    /**
     * 至多选择几张图片，默认一张
     */
    private int maxNumber = 0;

    private int minNumber = 0;// 图片最少选取几张

    private Context mContext;

    private TopLayout mTopLayout;

    /**
     * intent 参数
     */
    public static final String MAX_NUMBER_IMAGES = "maxImageNumber";// 图片最大选取数

    public static final String MIN_NUMBER_IMAGES = "minImageNumber";// 图片最小选取数

    /**
     * 是否支持多选文件
     */
    private boolean isSupportMultiSelected = false;

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        if (cameraPath != null && cameraPath.length() > 0)
        {
            outState.putString("cameraPath", cameraPath);
        }
    }

    @Override
    protected void onCreate(Bundle arg0)
    {
        super.onCreate(arg0);
        mContext = this;
        if (arg0 != null && arg0.containsKey("cameraPath"))
        {
            cameraPath = arg0.getString("cameraPath");
        }
        setContentView(R.layout.activity_select_fromlocal);
        Intent intent = getIntent();

        if (intent.hasExtra(MAX_NUMBER_IMAGES))
        {
            maxNumber = intent.getIntExtra(MAX_NUMBER_IMAGES, 1);
            isSupportMultiSelected = true;

        }
        else
        {
            maxNumber = 1;
            isSupportMultiSelected = false;
        }
        if (intent.hasExtra(MIN_NUMBER_IMAGES))
        {
            minNumber = intent.getIntExtra(MIN_NUMBER_IMAGES, 1);
        }
        else
        {
            minNumber = 1;
        }
        initView();
        startTask();
//        btn_tijiao.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                checkSelect();
//            }
//        });
    }

    @Override
    public BasePresenter getPresenter() {
        return null;
    }

    @Override
    protected void onNewIntent(Intent intent)
    {
        super.onNewIntent(intent);
        if (intent.hasExtra(MAX_NUMBER_IMAGES))
        {
            maxNumber = intent.getIntExtra(MAX_NUMBER_IMAGES, 1);
            isSupportMultiSelected = true;
        }
        else
        {
            maxNumber = 1;
            isSupportMultiSelected = false;

        }

        if (intent.hasExtra(MIN_NUMBER_IMAGES))
        {
            minNumber = intent.getIntExtra(MIN_NUMBER_IMAGES, 1);
        }
        else
        {
            minNumber = 1;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean persimmison = false;
        String permissionName = null;
        int size = permissions.length;

        for (int i = 0; i < size; i++)
        {
            permissionName = permissions[i];
            if (grantResults[i] == PackageManager.PERMISSION_DENIED)
            {
                persimmison = false;
                break;
            }
            else
            {
                persimmison = true;
            }
        }

        if (persimmison)
        {
            if (requestCode == READ_EXTERNAL_STORAGE)
            {
                loadLocalPicData();
            }
            else
            {
                takeCamera();
            }
        }
        else
        {
            String resultTip;
            if (permissionName == Manifest.permission.READ_EXTERNAL_STORAGE)
            {
                resultTip = "存储卡读取";

            }
            else
            {
                resultTip = "使用相机";

            }
            ToastUtils.showToast_Long(mContext, "没有" + resultTip + "权限");
        }
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        super.onCreateOptionsMenu(menu);
        menu.add(1, 1, 1, "确定").setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }

    private void initView()
    {

        mTopLayout = (TopLayout) findViewById(R.id.top_layout);
        gvFromLocal = (GridView)findViewById(R.id.gv_local_album);

        gvFromLocal.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                LocalPicListAdapter adapter = (LocalPicListAdapter)parent.getAdapter();
                ImportImageItem importImageItem = (ImportImageItem)adapter.getItem(position);
                if (importImageItem.isImageButton)
                {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
                    {

                        if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
                        {
                            if (checkSelfPermission(
                                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                            {
                                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.CAMERA}, TAKE_PHOTO_CODE);
                            }
                            else
                            {
                                requestPermissions(new String[] {Manifest.permission.CAMERA}, TAKE_PHOTO_CODE);
                            }
                        }
                        else
                        {
                            if (checkSelfPermission(
                                    Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                            {
                                requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE},
                                        TAKE_PHOTO_CODE);
                            }
                            else
                            {
                                takeCamera();
                            }
                        }
                    }
                    else
                    {
                        takeCamera();
                    }

                }
            }
        });

        mTopLayout.setOnRightTextClickLstener(getString(R.string.pic_do_select), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkSelect();
            }
        });
    }

    /**
     * 拍照功能
     */
    private String cameraPath = null;


    public File getNextFileName() {
        File mGalleryFolder = FileUtils.createFolders(FileUtils.IMAGE);
        if (mGalleryFolder != null) {
            if (mGalleryFolder.exists()) {
                File file = new File(mGalleryFolder, "cbclient_" + System.currentTimeMillis() + ".jpg");
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return file;
            }
        }
        return null;
    }

    private void takeCamera()
    {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED))
        {
            Intent getImageByCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = getNextFileName();
            cameraPath = file.getAbsolutePath();
            getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));

            startActivityForResult(getImageByCamera, TAKE_PHOTO_CODE);
        }
        else
        {
            ToastUtils.showToast_Short(mContext, "请确认已经插入SD卡");
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            Configuration o = newConfig;
            o.orientation = Configuration.ORIENTATION_PORTRAIT;
            newConfig.setTo(o);
        }
        else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
        {
        }
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 加载本地图片资源数据
     */
    private void loadLocalPicData()
    {
        mFindImageHelper = new FindImageHelper(this);
        if (mLoadDisplayTask != null)
            mLoadDisplayTask.cancel(true);
        mLoadDisplayTask = new LoadAndDisplayTask();
        mLoadDisplayTask.execute(1);
    }

    private void checkSelect()
    {
        if (listAdapter == null)
        {
            ToastUtils.showToast_Short(mContext, R.string.pic_img_no);
            return;
        }
        ArrayList<ImportImageItem> selectList = listAdapter.getSelectList();
        if (selectList == null || selectList.isEmpty())
        {
            ToastUtils.showToast_Short(mContext, R.string.pic_img_no);
        }
        else
        {
            int size = selectList.size();
            Intent intent = new Intent();

            if (isSupportMultiSelected)
            {
                if (size > maxNumber)
                {
                    int over = size - maxNumber;
                    ToastUtils.showToast_Short(mContext,
                            mContext.getResources().getString(R.string.pic_img_no_over, over + ""));
                    return;
                }

                intent.putExtra("imageItems", selectList);

            }
            else
            {
                ImportImageItem imageItem = selectList.get(0);
                intent.putExtra("imageItem", imageItem);
                writePicImagePath(imageItem);
            }
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void writePicImagePath(ImportImageItem imageItem){
        SharedPrefsHelp.getInstance().setSharedPrefs("imageItem",imageItem.getImage());
    }
    private void startTask()
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
            {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                {
                    requestPermissions(
                            new String[] {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                            READ_EXTERNAL_STORAGE);
                }
                else
                {
                    requestPermissions(new String[] {Manifest.permission.CAMERA}, READ_EXTERNAL_STORAGE);
                }
            }
            else
            {
                if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
                {
                    requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE);
                }
                else
                {
                    loadLocalPicData();
                }
            }
        }
        else
        {
            loadLocalPicData();
        }

    }

    /**
     * 载入需展示的数据
     *
     * @author panyi
     */
    private final class LoadAndDisplayTask extends AsyncTask<Integer, Void, ImportImagesData>
    {
        @Override
        protected ImportImagesData doInBackground(Integer... params)
        {
            ImportImagesData newData = null;
            try
            {
                System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
            }
            catch (Exception e)
            {
            }
            List<ImageDetailBean> imageList = mFindImageHelper.findImagesByFolder("");
            newData = new ImportImagesData(imageList, null);

            return newData;
        }

        @Override
        protected void onPostExecute(ImportImagesData result)
        {
            super.onPostExecute(result);
            data = result;
            if (data != null)
            {
                updateUI();
            }
        }

    }

    private void updateUI()
    {
        listAdapter = new LocalPicListAdapter(this, gvFromLocal, data.getList(), isSupportMultiSelected,maxNumber);
        gvFromLocal.setAdapter(listAdapter);
    }


//    @Override
//    public boolean onSupportNavigateUp() {
//        setResult(RESULT_CANCELED);
//
//        return super.onSupportNavigateUp();
//
//    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(RESULT_CANCELED);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK)
        {
            //拍照返回结果的处理，发广播实现
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_STARTED);
            intent.setData(
                    Uri.fromFile(new File(FileUtils.createFolders().getAbsolutePath() + File.separator + PREFIX + "/")));
            getApplication().sendBroadcast(intent);
            Intent importImageItemintent = new Intent();
            ImportImageItem importImageItem = new ImportImageItem();
            importImageItem.setImage(cameraPath);
            importImageItem.setDateTaken(System.currentTimeMillis());
            if (cameraPath != null && cameraPath.length() > 0)
            {
                File file = new File(cameraPath);

                long fileLength = file.length();
                importImageItem.setSize((int)fileLength);
                //writePicImagePath(importImageItem);

                importImageItemintent.putExtra("imageItem", importImageItem);

                ArrayList<ImportImageItem> imageItems = new ArrayList<ImportImageItem>();
                imageItems.add(importImageItem);
                importImageItemintent.putExtra("imageItems", imageItems);

                setResult(RESULT_OK, importImageItemintent);
                finish();

            }

        }
    }

}
// ┏┓ ┏┓
// ┏┛┻━━━┛┻┓
// ┃ ┃
// ┃ ━ ┃
// ┃ ┳┛ ┗┳ ┃
// ┃ ┃
// ┃ ┻ ┃
// ┃ ┃
// ┗━┓ ┏━┛
// ┃ ┃ 神兽保佑
// ┃ ┃ 代码无BUG！
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛